<template>
  <div class="user-roles">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">角色管理</span>
        </div>
      </template>
      
      <DataTable
        :data="tableData"
        :columns="columns"
        :loading="loading"
        :search-fields="searchFields"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :show-index="false"
        @add="handleAdd"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="handleSearch"
        @refresh="handleRefresh"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #permissions="{ row }">
          <el-tag
            v-for="permission in row.permissions.slice(0, 3)"
            :key="permission"
            size="small"
            style="margin-right: 4px; margin-bottom: 4px"
          >
            {{ permission }}
          </el-tag>
          <el-tag
            v-if="row.permissions.length > 3"
            size="small"
            type="info"
          >
            +{{ row.permissions.length - 3 }}
          </el-tag>
        </template>
        
        <template #status="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(row)"
          />
        </template>
        
        <template #row-actions="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="success" link @click="handlePermissions(row)">权限</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </DataTable>
    </el-card>
    
    <!-- 角色表单对话框 -->
    <FormDialog
      v-model="showDialog"
      :title="dialogTitle"
      :fields="formFields"
      :data="currentRole"
      :loading="submitLoading"
      @submit="handleSubmit"
      @close="handleDialogClose"
    />
    
    <!-- 权限配置对话框 -->
    <el-dialog
      v-model="showPermissionDialog"
      title="权限配置"
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="{ children: 'children', label: 'label' }"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
        @check="handlePermissionCheck"
      />
      
      <template #footer>
        <el-button @click="showPermissionDialog = false">取消</el-button>
        <el-button type="primary" :loading="permissionLoading" @click="handlePermissionSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import DataTable from '@/components/DataTable.vue'
import FormDialog from '@/components/FormDialog.vue'
import type { TableColumn, SearchField } from '@/components/DataTable.vue'
import type { FormField } from '@/components/FormDialog.vue'

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const showDialog = ref(false)
const dialogTitle = ref('')
const currentRole = ref<any>({})
const submitLoading = ref(false)

// 权限对话框状态
const showPermissionDialog = ref(false)
const permissionTreeRef = ref()
const checkedPermissions = ref<string[]>([])
const permissionLoading = ref(false)
const currentPermissionRole = ref<any>({})

// 表格列配置
const columns: TableColumn[] = [
  { prop: 'id', label: 'ID', width: 80 },
  { prop: 'name', label: '角色名称', minWidth: 120 },
  { prop: 'code', label: '角色代码', minWidth: 120 },
  { prop: 'description', label: '描述', minWidth: 200 },
  { prop: 'permissions', label: '权限', minWidth: 200, slot: 'permissions' },
  { prop: 'userCount', label: '用户数', width: 80 },
  { prop: 'status', label: '状态', width: 80, slot: 'status' },
  { prop: 'createdAt', label: '创建时间', width: 160 }
]

// 搜索字段配置
const searchFields: SearchField[] = [
  { prop: 'keyword', label: '关键词', type: 'input' },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  }
]

// 表单字段配置
const formFields: FormField[] = [
  { prop: 'name', label: '角色名称', type: 'input', required: true },
  { prop: 'code', label: '角色代码', type: 'input', required: true },
  { prop: 'description', label: '描述', type: 'textarea' },
  {
    prop: 'status',
    label: '状态',
    type: 'radio',
    required: true,
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  }
]

// 权限树数据
const permissionTree = ref([
  {
    id: 'user',
    label: '用户管理',
    children: [
      { id: 'user:read', label: '查看用户' },
      { id: 'user:write', label: '编辑用户' },
      { id: 'user:delete', label: '删除用户' }
    ]
  },
  {
    id: 'product',
    label: '商品管理',
    children: [
      { id: 'product:read', label: '查看商品' },
      { id: 'product:write', label: '编辑商品' },
      { id: 'product:delete', label: '删除商品' }
    ]
  },
  {
    id: 'order',
    label: '订单管理',
    children: [
      { id: 'order:read', label: '查看订单' },
      { id: 'order:write', label: '编辑订单' },
      { id: 'order:delete', label: '删除订单' }
    ]
  },
  {
    id: 'system',
    label: '系统管理',
    children: [
      { id: 'system:role', label: '角色管理' },
      { id: 'system:permission', label: '权限管理' },
      { id: 'system:setting', label: '系统设置' }
    ]
  }
])

// 模拟数据
const mockRoles = [
  {
    id: 1,
    name: '超级管理员',
    code: 'super_admin',
    description: '拥有系统所有权限',
    permissions: ['user:read', 'user:write', 'user:delete', 'product:read', 'product:write', 'product:delete', 'order:read', 'order:write', 'order:delete', 'system:role', 'system:permission', 'system:setting'],
    userCount: 1,
    status: 1,
    createdAt: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '管理员',
    code: 'admin',
    description: '拥有业务管理权限',
    permissions: ['user:read', 'user:write', 'product:read', 'product:write', 'order:read', 'order:write'],
    userCount: 3,
    status: 1,
    createdAt: '2024-01-02 14:20:00'
  },
  {
    id: 3,
    name: '编辑',
    code: 'editor',
    description: '拥有内容编辑权限',
    permissions: ['product:read', 'product:write', 'order:read'],
    userCount: 5,
    status: 1,
    createdAt: '2024-01-03 11:15:00'
  },
  {
    id: 4,
    name: '普通用户',
    code: 'user',
    description: '基础用户权限',
    permissions: ['user:read', 'product:read', 'order:read'],
    userCount: 20,
    status: 1,
    createdAt: '2024-01-04 16:30:00'
  }
]

// 获取角色列表
const fetchRoles = async (params: any = {}) => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = [...mockRoles]
    
    if (params.keyword) {
      filteredData = filteredData.filter(role =>
        role.name.includes(params.keyword) ||
        role.code.includes(params.keyword) ||
        role.description.includes(params.keyword)
      )
    }
    
    if (params.status !== undefined && params.status !== '') {
      filteredData = filteredData.filter(role => role.status === params.status)
    }
    
    total.value = filteredData.length
    
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  currentRole.value = { status: 1 }
  showDialog.value = true
}

// 处理编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑角色'
  currentRole.value = { ...row }
  showDialog.value = true
}

// 处理删除
const handleDelete = async (row: any) => {
  if (row.userCount > 0) {
    ElMessage.warning('该角色下还有用户，无法删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除角色 "${row.name}" 吗？`, '确认删除', {
      type: 'warning'
    })
    
    ElMessage.success('删除成功')
    fetchRoles()
  } catch (error) {
    // 用户取消删除
  }
}

// 处理状态变化
const handleStatusChange = async (row: any) => {
  try {
    await new Promise(resolve => setTimeout(resolve, 300))
    ElMessage.success('状态更新成功')
  } catch (error) {
    row.status = row.status === 1 ? 0 : 1 // 回滚状态
    ElMessage.error('状态更新失败')
  }
}

// 处理权限配置
const handlePermissions = (row: any) => {
  currentPermissionRole.value = row
  checkedPermissions.value = row.permissions
  showPermissionDialog.value = true
}

// 处理权限选择
const handlePermissionCheck = (data: any, checked: any) => {
  // 权限选择逻辑
}

// 处理权限提交
const handlePermissionSubmit = async () => {
  permissionLoading.value = true
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys]
    
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新角色权限
    const roleIndex = tableData.value.findIndex(role => role.id === currentPermissionRole.value.id)
    if (roleIndex !== -1) {
      tableData.value[roleIndex].permissions = allCheckedKeys
    }
    
    ElMessage.success('权限配置成功')
    showPermissionDialog.value = false
  } catch (error) {
    ElMessage.error('权限配置失败')
  } finally {
    permissionLoading.value = false
  }
}

// 处理搜索
const handleSearch = (params: any) => {
  currentPage.value = 1
  fetchRoles(params)
}

// 处理刷新
const handleRefresh = () => {
  fetchRoles()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchRoles()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchRoles()
}

// 处理表单提交
const handleSubmit = async (data: any) => {
  submitLoading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success(currentRole.value.id ? '更新成功' : '创建成功')
    showDialog.value = false
    fetchRoles()
  } catch (error) {
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 处理对话框关闭
const handleDialogClose = () => {
  currentRole.value = {}
}

onMounted(() => {
  fetchRoles()
})
</script>

<style lang="scss" scoped>
.user-roles {
  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
  }
}
</style>
